package com.loie.datacenter.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.loie.datacenter.comm.CommJSON;
import com.loie.datacenter.comm.ExcelConst;
import com.loie.datacenter.model.bo.*;
import com.loie.datacenter.service.OrderService;
import com.loie.datacenter.service.UserListService;
import com.loie.datacenter.util.ExcelUtil;
import com.loie.datacenter.util.SecureUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhl
 * @create 2021/9/11 19:55
 */
@Slf4j
@RequestMapping("/order")
@RestController
@AllArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final RedisTemplate<String, String> redisTemplate;
    private final UserListService userListService;

    @PostMapping("/getOrderDetail")
    public
    CommJSON getOrderDetail(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO) {
        CommJSON commJson = new CommJSON();
        try {
            String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                    tokenInfoBO.getToken())));
            String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
            OrderItemBO bo = JSONObject.parseObject(mwMsg, OrderItemBO.class);

            List<OrderItemBO> datalist = orderService.getOrderItemList(bo);
            OrderItemSumBO orderItemSumBO = orderService.getOrderItemSum(bo);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", datalist);
            String orderQtySum = orderItemSumBO.getOrderQtySum();
            String salesAmountSum = orderItemSumBO.getSalesAmountSum();
            String cartonQtySum = orderItemSumBO.getCartonQtySum();
            String volumeSum = orderItemSumBO.getVolumeSum();
            String shippingQtySum = orderItemSumBO.getShippingQtySum();
            String unShippingQtySum = orderItemSumBO.getUnShippingQtySum();

            jsonObject.put("orderQtySum", orderQtySum == null ? 0 : orderQtySum);
            jsonObject.put("salesAmountSum", salesAmountSum == null ? 0 : salesAmountSum);
            jsonObject.put("cartonQtySum", cartonQtySum == null ? 0 : cartonQtySum);
            jsonObject.put("volumeSum", volumeSum == null ? 0 : volumeSum);
            jsonObject.put("shippingQtySum", shippingQtySum == null ? 0 : shippingQtySum);
            jsonObject.put("unShippingQtySum", unShippingQtySum == null ? 0 : unShippingQtySum);
            commJson.setSuc();
            commJson.setData(SecureUtil.encryptAES(jsonObject.toJSONString(), aesSecureKey));
        } catch (Exception e) {
            commJson.setErrorMessage("Sorry, Query exception(code:1102)");
            commJson.setError();
            e.printStackTrace();
            log.error("OrderController.getOrderDetail()===>", e);
        }
        return commJson;
    }

    @PostMapping("/getOrderList")
    public
    CommJSON getOrderList(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO) {
        CommJSON commJson = new CommJSON();
        try {
            String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                    tokenInfoBO.getToken())));
            String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
            OrderBO bo = JSONObject.parseObject(mwMsg, OrderBO.class);
            List<OrderBO> dataList = orderService.getOrderList(bo, tokenInfoBO.getUser());
            JSONObject jsonObject = new JSONObject();
            OrderItemSumBO orderItemSumBO = orderService.getOrderCount(bo, tokenInfoBO.getUser());
            jsonObject.put("total", orderItemSumBO.getTotal());
            String totalSalesAmount = orderItemSumBO.getTotalSalesAmount();
            String hiddenCommSum = orderItemSumBO.getHiddenCommSum();
            jsonObject.put("totalSalesAmount", totalSalesAmount == null ? 0 : totalSalesAmount);
            jsonObject.put("hiddenCommSum", hiddenCommSum == null ? 0 : hiddenCommSum);
            jsonObject.put("list", dataList);

            commJson.setSuccess(true);
            commJson.setData(SecureUtil.encryptAES(jsonObject.toJSONString(), aesSecureKey));
        } catch (Exception e) {
            commJson.setErrorMessage("Sorry, Query exception(code:1101)");
            commJson.setError();
            e.printStackTrace();
            log.error("OrderController.getOrderList()===>", e);
        }
        return commJson;
    }

    /**
     * 导出参加信息表
     *
     * @param res
     * @throws Exception
     */
    @PostMapping(value = "/downloadOrderList")
    public void downloadTaskInfo(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO, HttpServletResponse res) throws Exception {
        try {
            String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                    tokenInfoBO.getToken())));

            UserListBO userListBO = userListService.getUserInfoByUser(tokenInfoBO.getUser());
            String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
            OrderBO bo = JSONObject.parseObject(mwMsg, OrderBO.class);
            bo.setPageIndex(-1);
            List<OrderBO> dataList = orderService.getOrderList(bo, tokenInfoBO.getUser());
            List<JSONObject> headList = new ArrayList<>();
            int authority = userListBO.getDataAuthority();

            List<List<String>> lists = new ArrayList<>();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "S/C NO.");
            jsonObject.put(ExcelConst.WIDTH, 3500);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "PO NO.");
            jsonObject.put(ExcelConst.WIDTH, 3500);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);


            if (authority == 2) {
                jsonObject = new JSONObject();
                jsonObject.put(ExcelConst.TITLE, "Customer Name");
                jsonObject.put(ExcelConst.WIDTH, 5000);
                jsonObject.put(ExcelConst.TYPE, "1");
                headList.add(jsonObject);
            }
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "S/C Date");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);

            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Delivery Date");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Trade Term");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "POL");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "POD");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Payment Term");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Currency");
            jsonObject.put(ExcelConst.WIDTH, 2000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Amount");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Commission Amount");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            headList.add(jsonObject);
            if ("3".equals(bo.getStatus())) {
                jsonObject = new JSONObject();
                jsonObject.put(ExcelConst.TITLE, "Remark");
                jsonObject.put(ExcelConst.WIDTH, 5000);
                jsonObject.put(ExcelConst.TYPE, "1");
                headList.add(jsonObject);
            }

            for (int i = 0; i < dataList.size(); i++) {
                List<String> list = new ArrayList<>();
                list.add(dataList.get(i).getSalesOrderNo());
                list.add(dataList.get(i).getCustomerContractNo());
                if (authority == 2) {
                    list.add(dataList.get(i).getCustomerCorpName());
                }
                list.add(dataList.get(i).getOrderDate());
                list.add(dataList.get(i).getDeliveryDate());
                list.add(dataList.get(i).getTermOfPrice());
                list.add(dataList.get(i).getLoadingPort());
                list.add(dataList.get(i).getDestinationPort());
                list.add(dataList.get(i).getPayment());
                list.add(dataList.get(i).getCurrency());
                list.add(dataList.get(i).getTotalSalesAmount());
                list.add(dataList.get(i).getHiddenComm());
                if ("3".equals(bo.getStatus())) {
                    list.add(dataList.get(i).getStatusMemo());
                }
                lists.add(list);
            }
            ExcelUtil.getExcel(res, lists, headList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("OrderController.downloadTaskInfo()===>", e);
        }
    }
    /**
     * 导出带明细信息表
     *
     * @param res
     * @throws Exception
     */
    @PostMapping(value = "/downloadOrderItemList")
    public void downloadOrderItemList(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO, HttpServletResponse res) throws Exception {
        try {
            String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                    tokenInfoBO.getToken())));

            UserListBO userListBO = userListService.getUserInfoByUser(tokenInfoBO.getUser());
            String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
            OrderBO bo = JSONObject.parseObject(mwMsg, OrderBO.class);
            bo.setPageIndex(-1);
            List<OrderWithItemBO> dataList = orderService.getOrderWithItemList(bo, tokenInfoBO.getUser());
            List<JSONObject> headList = new ArrayList<>();
            int authority = userListBO.getDataAuthority();

            List<List<String>> lists = new ArrayList<>();
            List<List<String>> cellRangeLists = new ArrayList<>();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "S/C NO.");
            jsonObject.put(ExcelConst.WIDTH, 3500);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "PO NO.");
            jsonObject.put(ExcelConst.WIDTH, 3500);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);


            if (authority == 2) {
                jsonObject = new JSONObject();
                jsonObject.put(ExcelConst.TITLE, "Customer Name");
                jsonObject.put(ExcelConst.WIDTH, 5000);
                jsonObject.put(ExcelConst.TYPE, "1");
                jsonObject.put(ExcelConst.MERGE,"1");
                headList.add(jsonObject);
            }
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "S/C Date");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);

            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Delivery Date");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Trade Term");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "POL");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "POD");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Payment Term");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Currency");
            jsonObject.put(ExcelConst.WIDTH, 2000);
            jsonObject.put(ExcelConst.TYPE, "1");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Amount");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Commission Amount");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            jsonObject.put(ExcelConst.MERGE,"1");
            headList.add(jsonObject);
            if ("3".equals(bo.getStatus())) {
                jsonObject = new JSONObject();
                jsonObject.put(ExcelConst.TITLE, "Remark");
                jsonObject.put(ExcelConst.WIDTH, 5000);
                jsonObject.put(ExcelConst.TYPE, "1");
                jsonObject.put(ExcelConst.MERGE,"1");
                headList.add(jsonObject);
            }

            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "ItemNo.");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "CustomerItemNo.");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Product Name");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Order Qty");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Unit");
            jsonObject.put(ExcelConst.WIDTH, 2000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Sales Price");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.0000");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Sales Amount");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Packing");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Pieces Per Carton");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Carton Qty");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "CBM");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.000");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Shipped Qty");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Unshipped Qty");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0");
            headList.add(jsonObject);



            for (int i = 0; i < dataList.size(); i++) {
                List<String> list = new ArrayList<>();
                list.add(dataList.get(i).getSalesOrderNo());
                list.add(dataList.get(i).getCustomerContractNo());
                if (authority == 2) {
                    list.add(dataList.get(i).getCustomerCorpName());
                }
                list.add(dataList.get(i).getOrderDate());
                list.add(dataList.get(i).getDeliveryDate());
                list.add(dataList.get(i).getTermOfPrice());
                list.add(dataList.get(i).getLoadingPort());
                list.add(dataList.get(i).getDestinationPort());
                list.add(dataList.get(i).getPayment());
                list.add(dataList.get(i).getCurrency());
                list.add(dataList.get(i).getTotalSalesAmount());
                list.add(dataList.get(i).getHiddenComm());
                if ("3".equals(bo.getStatus())) {
                    list.add(dataList.get(i).getStatusMemo());
                }

                list.add(dataList.get(i).getItemNo());
                list.add(dataList.get(i).getCustomerItemNo());
                list.add(dataList.get(i).getEngItemName());
                list.add(dataList.get(i).getOrderQty());
                list.add(dataList.get(i).getUnit());
                list.add(dataList.get(i).getSalesPrice());
                list.add(dataList.get(i).getSalesAmount());
                list.add(dataList.get(i).getEngPacking());
                list.add(dataList.get(i).getOuterCapacity());
                list.add(dataList.get(i).getCartonQty());
                list.add(dataList.get(i).getVolume());
                list.add(dataList.get(i).getShippingQty());
                list.add(dataList.get(i).getUnShippingQty());
                lists.add(list);

                List<String> cellList = new ArrayList<>();
                cellList.add(dataList.get(i).getSalesOrderNo());
                cellRangeLists.add(cellList);
            }
            ExcelUtil.getExcelWithCellRange(res, lists, headList,cellRangeLists);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("OrderController.downloadOrderItemList()===>", e);
        }
    }
}
